<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>乞丐版Generator</title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}
		</style>
	</head>

	<body>
		<script>
			function* foo() {
				yield "result1";
				yield "result2";
				yield "result3";
			}

			//以下是编译器解释出来的

			function gen$(_context) {
				while (1) {
					switch ((_context.prev = _context.next)) {
						case 0:
							_context.next = 1;
							return "result1";

						case 1:
							_context.next = 2;
							return "result2";

						case 2:
							_context.next = 3;
							return "result3";

						case 3:
							return _context.stop();
					}
				}
			}

			// 低配版context
			const context = {
				next: 0,
				prev: 0,
				done: false,
				stop() {
					this.done = true;
				},
			};

			// 低配版invoke
			const invoke = function () {
				return {
					next() {
						value = context.done ? undefined : gen$(context);
						done = context.done;
						return {
							value,
							done,
						};
					},
				};
			};

			const gen = invoke();
			for (let index = 0; index < 4; index++) {
				console.log(gen.next());
			}
		</script>
	</body>
</html>
